//
//  DJLoginViewController.m
//  DualJoy
//
//  Created by lijunge on 2019/11/14.
//  Copyright © 2019 lijunge. All rights reserved.
//

#import "DJLoginViewController.h"
#import "DJHomeViewController.h"
#import "DJConstant.h"
#import <Masonry.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <GoogleSignIn/GoogleSignIn.h>
#import "WXApi.h"
#import "DJHttpManager.h"
#import "DJWebViewController.h"
#import "ProgressHUD.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "SignInApple.h"

@interface DJLoginViewController ()<UITextViewDelegate,GIDSignInDelegate,WXApiDelegate,SignInDelegate>

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UITextField *userNameField;
@property (nonatomic, strong) UITextField *passwordField;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *googleButton;
@property (nonatomic, strong) UIView *loginView;
@property (nonatomic, strong) SignInApple *signInApple;

@end

@implementation DJLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = kVCBackColor;
    [self configSubViews];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxLogin:) name:@"wxLogin" object:NULL];
}

- (void)configSubViews {
    
    UIImageView *backImageView = [[UIImageView alloc] init];
    backImageView.image = [UIImage imageNamed:@"launchImage"];
    backImageView.userInteractionEnabled = YES;
    [self.view addSubview:backImageView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backTapGestureTapped)];
    [backImageView addGestureRecognizer:tapGesture];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"KALEIDOSCOPE";
    self.titleLabel.font = [UIFont boldSystemFontOfSize:30];
    self.titleLabel.backgroundColor = [UIColor clearColor];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.titleLabel];

    UIButton *wechatButton = [[UIButton alloc] init];
    [wechatButton setTitle:@"Wechat" forState:UIControlStateNormal];
    [wechatButton setImage:[UIImage imageNamed:@"weixin_login"] forState:UIControlStateNormal];
    wechatButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    wechatButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [wechatButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [wechatButton addTarget:self action:@selector(wechatLoginButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wechatButton];
    
    UIButton *facebookButton = [[UIButton alloc] init];
    [facebookButton setTitle:@"Facebook" forState:UIControlStateNormal];
    [facebookButton setImage:[UIImage imageNamed:@"facebook_login"] forState:UIControlStateNormal];
    facebookButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    facebookButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [facebookButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [facebookButton addTarget:self action:@selector(facebookLoginButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:facebookButton];
    
    self.googleButton = [[UIButton alloc] init];
    [self.googleButton setTitle:@"Google" forState:UIControlStateNormal];
    [self.googleButton setImage:[UIImage imageNamed:@"google_login_2"] forState:UIControlStateNormal];
    self.googleButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.googleButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [self.googleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.googleButton addTarget:self action:@selector(googleLoginButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.googleButton];
    
    NSString *tmpString = @"登录即表示同意我们的用户协议和隐私政策";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"登录即表示同意我们的用户协议和隐私政策"];
    NSRange protocolRange = [[attributedString string] rangeOfString:@"用户协议"];
    NSRange privacyRange = [[attributedString string] rangeOfString:@"隐私政策"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"protocol://"
                             range:protocolRange];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"privacy://"
                             range:privacyRange];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, tmpString.length)];
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(1) range:protocolRange];
    [attributedString addAttribute:NSUnderlineStyleAttributeName value:@(1) range:privacyRange];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:protocolRange];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:privacyRange];
    CGFloat stringWidth = [tmpString sizeWithAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:12]}].width;
    
    UITextView *privacyTextView = [[UITextView alloc] init];
    privacyTextView.editable = NO;
    privacyTextView.backgroundColor = [UIColor clearColor];
    privacyTextView.selectable = YES;
    privacyTextView.scrollEnabled = NO;
    privacyTextView.textColor = [UIColor whiteColor];
    privacyTextView.dataDetectorTypes = UIDataDetectorTypeLink;
    privacyTextView.contentSize = CGSizeMake(self.view.frame.size.width, 40);
    privacyTextView.textContainer.lineFragmentPadding = 0.0;
    privacyTextView.textContainerInset = UIEdgeInsetsMake(10, 0, 0, 0);
    privacyTextView.delegate = self;
    privacyTextView.textAlignment = NSTextAlignmentCenter;
    privacyTextView.linkTextAttributes = @{NSForegroundColorAttributeName: KScienceTechnologyBlue};
    privacyTextView.attributedText = attributedString;
    [self.view addSubview:privacyTextView];
    
    int count = [WXApi isWXAppInstalled] ? 3 : 2;
    CGFloat buttonWH = 100;
    CGFloat alignMargin = (self.view.frame.size.width - count * buttonWH) / (count + 1);
    
    [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kDJNavBarHeight + 80);
        make.height.mas_equalTo(50);
        make.left.right.equalTo(self.view);
    }];
    
    [privacyTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(stringWidth);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(self.view.mas_bottom).offset(-40);
    }];

    [wechatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(buttonWH);
        make.height.mas_equalTo(buttonWH);
        make.left.equalTo(self.view).offset(alignMargin);
        make.bottom.equalTo(privacyTextView.mas_top).offset(-40);
    }];

    [facebookButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(wechatButton.mas_right).offset(alignMargin);
        make.width.mas_equalTo(buttonWH);
        make.height.mas_equalTo(buttonWH);
        make.bottom.equalTo(wechatButton);
    }];

    [self.googleButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(facebookButton.mas_right).offset(alignMargin);
        make.width.mas_equalTo(buttonWH);
        make.height.mas_equalTo(buttonWH);
        make.bottom.equalTo(wechatButton);
    }];
    
    if (![WXApi isWXAppInstalled]) {
        [wechatButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(0);
            make.width.height.mas_equalTo(0);
        }];
        [self adjustButtonImageAndTitleLabelEdge:facebookButton];
        [self adjustButtonImageAndTitleLabelEdge:self.googleButton];
    } else {
        [self adjustButtonImageAndTitleLabelEdge:wechatButton];
        [self adjustButtonImageAndTitleLabelEdge:facebookButton];
        [self adjustButtonImageAndTitleLabelEdge:self.googleButton];
    }
    
    [self configAppOnline];
    [self configAppleSignIn];
}

- (void)configTestLoginView {

    self.userNameField = [[UITextField alloc] init];
    self.userNameField.placeholder = @"请输入用户名";
    self.userNameField.backgroundColor = [UIColor whiteColor];
    self.userNameField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.userNameField];
    
    self.passwordField = [[UITextField alloc] init];
    self.passwordField.placeholder = @"请输入密码";
    self.passwordField.backgroundColor = [UIColor whiteColor];
    self.passwordField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.passwordField];
    
    self.loginButton = [[UIButton alloc] init];
    self.loginButton.backgroundColor = [UIColor whiteColor];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:KScienceTechnologyBlue forState:UIControlStateNormal];
    self.loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:22];
    self.loginButton.layer.cornerRadius = 5.0;
    [self.loginButton addTarget:self action:@selector(loginButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginButton];
    
    CGFloat topMargin = kDJScreenWidthScale * 20;
    [self.userNameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(40);
        make.right.equalTo(self.view).offset(-40);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(topMargin);
    }];
    
    [self.passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(40);
        make.right.equalTo(self.view).offset(-40);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.userNameField.mas_bottom).offset(10);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(40);
        make.right.equalTo(self.view).offset(-40);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.passwordField.mas_bottom).offset(10);
    }];
}

- (void)configAppleSignIn {
    
    if (@available(iOS 13.0, *)) {
        // Sign In With Apple Button
        ASAuthorizationAppleIDButton *appleIDBtn = [ASAuthorizationAppleIDButton buttonWithType:ASAuthorizationAppleIDButtonTypeDefault style:ASAuthorizationAppleIDButtonStyleWhite];
        [appleIDBtn addTarget:self action:@selector(didAppleIDBtnClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:appleIDBtn];
        [appleIDBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).offset(40);
            make.right.equalTo(self.view).offset(-40);
            make.height.mas_equalTo(40);
            make.bottom.equalTo(self.googleButton.mas_top).offset(-20);
        }];
    }
    
}

- (void)configAppOnline {
    
    NSString *urlStr = [NSString stringWithFormat:@"http://3.112.73.171/adtiming/online"];
    [DJHttpManager get:urlStr params:@{} success:^(NSDictionary * _Nonnull result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (![DJTool validObj:result]) {
                return;
            }
            int code = [[result valueForKey:@"code"] intValue];
            if (code != 0) {
                return;
            }
            BOOL online = [[result valueForKey:@"online"] boolValue];
            if (!online) {
                [self configTestLoginView];
            }
        });
    } failure:^(NSDictionary * _Nonnull error) {
        [self showErrorAlertViewWithTitle:@"登录失败,连接不上服务器"];
    }];
}

- (void)adjustButtonImageAndTitleLabelEdge:(UIButton *)button {
   
    CGFloat spacing = 6.0;
    CGSize imageSize = button.imageView.image.size;
    button.titleEdgeInsets = UIEdgeInsetsMake(0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);

    CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
    button.imageEdgeInsets = UIEdgeInsetsMake(- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
    
    CGFloat edgeOffset = fabs(titleSize.height - imageSize.height) / 2.0;
    button.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);
}

- (void)showErrorAlertViewWithTitle:(NSString *)title {

    [ProgressHUD showError:title];
}

- (void)loginWithWeixin:(NSString *)userID {
    
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:@1 forKey:@"login_type"];
    [params setValue:userID forKey:@"user_id"];
    [self loginKaleidoWithUserID:userID type:@"1" params:params];
}

- (void)loginWithFacebook:(NSString *)userID {
    
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:@2 forKey:@"login_type"];
    [params setValue:userID forKey:@"user_id"];
    [self loginKaleidoWithUserID:userID type:@"2" params:params];
}

- (void)loginWithGoogleSignIn:(NSString *)userID {
    
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:@3 forKey:@"login_type"];
    [params setValue:userID forKey:@"user_id"];
    [self loginKaleidoWithUserID:userID type:@"3" params:params];
}

- (void)loginKaleidoWithUserID:(NSString *)userID
                          type:(NSString *)type
                        params:(NSDictionary *)params {
    
    if (![DJTool validStr:userID]) {
        [self showErrorAlertViewWithTitle:@"登录失败，请稍后尝试"];
        return;
    }
    [ProgressHUD show];
    NSString *urlStr = [NSString stringWithFormat:@"http://3.112.73.171/adtiming/login"];
    [DJHttpManager post:urlStr params:params success:^(NSDictionary * _Nonnull result) {
        NSLog(@"注册%@-%@",result,userID);
        dispatch_async(dispatch_get_main_queue(), ^{
            [ProgressHUD dismiss];
            if (![DJTool validObj:result]) {
                [self showErrorAlertViewWithTitle:@"登录失败，请稍后尝试"];
                return;
            }
            int code = [[result valueForKey:@"code"] intValue];
            if (code != 0) {
                [self showErrorAlertViewWithTitle:@"登录失败，请稍后尝试"];
                return;
            }
            if (type.intValue == 4) {
                NSMutableDictionary *userDic = [NSMutableDictionary new];
                if ([DJTool validStr:userID]) {
                    [userDic setValue:userID forKey:@"user_id"];
                }
                if ([DJTool validStr:userID]) {
                    [userDic setValue:userID forKey:@"user_name"];
                }
                if ([DJTool validStr:@""]) {
                    [userDic setValue:@"" forKey:@"user_image"];
                }
                [userDic setValue:@"4" forKey:@"user_type"];
                [[NSUserDefaults standardUserDefaults] setValue:userDic forKey:@"user_info"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"DualJoyLogin"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            DJHomeViewController *homeVC = [[DJHomeViewController alloc] init];
            homeVC.userID = userID;
            homeVC.userType = type;
            [self.navigationController pushViewController:homeVC animated:YES];
        });
    } failure:^(NSDictionary * _Nonnull error) {
        NSLog(@"[loginDualJoyWithParams] error: %@", error);
        [self showErrorAlertViewWithTitle:@"登录失败,连接不上服务器"];
    }];
}

- (void)loginWithApple:(NSMutableDictionary *)info {
    
    [ProgressHUD show];
    NSString *identityTokenString = [info valueForKey:@"identity_token"];
    NSString *userString = [info valueForKey:@"user_id"];
    if (![DJTool validStr:identityTokenString]) {
        [self showErrorAlertViewWithTitle:@"Apple 登录失败"];
        return;
    }
    if (![DJTool validStr:userString]) {
        [self showErrorAlertViewWithTitle:@"Apple 登录失败"];
        return;
    }
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:identityTokenString forKey:@"identity_token"];
    [params setValue:userString forKey:@"user"];
    NSString *urlStr = [NSString stringWithFormat:@"http://3.112.73.171/adtiming/apple/login"];
    [DJHttpManager post:urlStr params:params success:^(NSDictionary * _Nonnull result) {
        NSLog(@"苹果登录%@",result);
        dispatch_async(dispatch_get_main_queue(), ^{
            [ProgressHUD dismiss];
            if (![DJTool validObj:result]) {
                [self showErrorAlertViewWithTitle:@"登录失败，请稍后尝试"];
                return;
            }
            int code = [[result valueForKey:@"code"] intValue];
            if (code != 0) {
                [self showErrorAlertViewWithTitle:@"登录失败，请稍后尝试"];
                return;
            }
            NSDictionary *dataInfo = result[@"data"];
            NSString *email = dataInfo[@"email"];
            [info setValue:email forKey:@"user_name"];
            [info setValue:email forKey:@"email"];
            NSMutableDictionary *loginParams = [NSMutableDictionary new];
            [loginParams setValue:@5 forKey:@"login_type"];
            [loginParams setValue:userString forKey:@"user_id"];
            [[NSUserDefaults standardUserDefaults] setValue:info forKey:@"user_info"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self loginKaleidoWithUserID:userString type:@"5" params:loginParams];
        });
    } failure:^(NSDictionary * _Nonnull error) {
        NSLog(@"[loginDualJoyWithParams] error: %@", error);
        [self showErrorAlertViewWithTitle:@"登录失败,连接不上服务器"];
    }];
}

#pragma mark - Notification
- (void)wxLogin:(NSNotification *)notification {//第三方登录
    
    NSLog(@"我收到微信登录的信息 通知了");
    SendAuthResp *resp = notification.object;
    [self getWeiXinOpenIdWithCode:resp.code];
}

//通过code获取access_token，openid，unionid
- (void)getWeiXinOpenIdWithCode:(NSString *)code{
    /*
     appid         是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret        是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code          是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWeiXinKey,kWeiXinSecret,code];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
            [self showErrorAlertViewWithTitle:@"微信授权失败"];
            return ;
        }
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSString *access_token = dic[@"access_token"];
        NSString *openid = dic[@"openid"];
        
        // 获取微信用户信息
        [self getUserInfoWithAccessToken:access_token WithOpenid:openid];
        
    });
}

- (void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid {
    
    NSString *url = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 获取用户信息失败
            if (!data) {
                [self showErrorAlertViewWithTitle:@"微信授权失败"];
                return ;
            }
            // 获取用户信息字典
            NSError *error;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            if ([DJTool validObj:dic] && error == nil) {
                //用户信息中没有access_token 我将其添加在字典中
                [dic setValue:access_token forKey:@"token"];
                NSMutableDictionary *userDic = [NSMutableDictionary new];
                NSString *userId = [dic valueForKey:@"unionid"];
                NSString *fullName = [dic valueForKey:@"nickname"];
                NSString *headImgUrl = [dic valueForKey:@"headimgurl"];
                if ([DJTool validStr:userId]) {
                    [userDic setValue:userId forKey:@"user_id"];
                }
                if ([DJTool validStr:fullName]) {
                    [userDic setValue:fullName forKey:@"user_name"];
                }
                if ([DJTool validStr:headImgUrl]) {
                    [userDic setValue:headImgUrl forKey:@"user_image"];
                }
                [userDic setValue:@"1" forKey:@"user_type"];
                [[NSUserDefaults standardUserDefaults] setValue:userDic forKey:@"user_info"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self loginWithWeixin:userId];
            } else {
                [self showErrorAlertViewWithTitle:@"微信登录个人信息获取失败"];
            }
        });
        
    });
    
}
#pragma mark - Action

- (void)loginButtonTapped:(UIButton *)sender {
    
    [self.userNameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
    
    if ([self.userNameField.text isEqualToString:@""]) {
        [self showErrorAlertViewWithTitle:@"请输入用户名"];
        return;
    }
    
    if ([self.passwordField.text isEqualToString:@""]) {
        [self showErrorAlertViewWithTitle:@"请输入密码"];
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:@4 forKey:@"login_type"];
    [params setValue:self.passwordField.text forKey:@"password"];
    [params setValue:self.userNameField.text forKey:@"user_id"];
    [self loginKaleidoWithUserID:self.userNameField.text type:@"4" params:params];
}

- (void)didAppleIDBtnClicked {
    
    self.signInApple = [[SignInApple alloc] init];
    self.signInApple.delegate = self;
    [self.signInApple handleAuthorizationAppleIDButtonPress];
}

- (void)backTapGestureTapped {
    
    [self.userNameField resignFirstResponder];
    [self.passwordField resignFirstResponder];
}

- (void)wechatLoginButtonTapped:(UIButton *)sender {
    
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.state = @"wx_oauth_authorization_state";
        req.scope = @"snsapi_userinfo";
        [WXApi sendReq:req completion:^(BOOL success) {
        }];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:actionConfirm];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)facebookLoginButtonTapped:(UIButton *)sender {
    
    [FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
    [FBSDKAccessToken setCurrentAccessToken:nil];
    
    FBSDKLoginManager *faceManager = [[FBSDKLoginManager alloc] init];
    [faceManager logOut];
    [faceManager logInWithPermissions:@[@"public_profile"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            [self showErrorAlertViewWithTitle:@"Facebook登录授权失败"];
            return;
        } else if (result.isCancelled) {
            NSLog(@"[LoginViewController] loginPermission cancel");
        } else {
            NSLog(@"[LoginViewController] loginPermission appID%@ - userID%@",[FBSDKAccessToken currentAccessToken].appID,[FBSDKAccessToken currentAccessToken].userID);
            NSString *userID = result.token.userID;
            NSMutableDictionary *userDic = [NSMutableDictionary new];
            if ([DJTool validStr:userID]) {
                [userDic setValue:userID forKey:@"user_id"];
            }
            [userDic setValue:@"2" forKey:@"user_type"];
            [[NSUserDefaults standardUserDefaults] setValue:userDic forKey:@"user_info"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self loginWithFacebook:userID];
        }
    }];
    
}

- (void)googleLoginButtonTapped:(UIButton *)sender {

    GIDSignIn *googleSign = [GIDSignIn sharedInstance];
    googleSign.shouldFetchBasicProfile = YES;
    googleSign.delegate = self;
    googleSign.presentingViewController = self;
    [googleSign signIn];
}

#pragma mark - SignInDelegate

- (void)signInDidFailWithInfo:(NSString *)error {
    
    [self showErrorAlertViewWithTitle:error];
}

- (void)signInDidSuccessWithInfo:(NSMutableDictionary *)info {
    
    [self loginWithApple:info];
}

#pragma mark - GIDDelegate
- (void)signIn:(GIDSignIn *)signIn didSignInForUser:(GIDGoogleUser *)user withError:(NSError *)error {
    
    if (error != nil) {
        [self showErrorAlertViewWithTitle:@"Google登录失败"];
        return;
    }
    NSString *userId = user.userID;
    NSString *fullName = user.profile.name;
    NSString *email = user.profile.email;
    NSMutableDictionary *dic = [NSMutableDictionary new];
    if ([DJTool validStr:userId]) {
        [dic setValue:userId forKey:@"user_id"];
    }
    if ([DJTool validStr:fullName]) {
        [dic setValue:fullName forKey:@"user_name"];
    }
    if ([DJTool validStr:email]) {
        [dic setValue:email forKey:@"user_email"];
    }
    if (user.profile.hasImage) {
        NSURL *headImageURL = [user.profile imageURLWithDimension:50];
        if ([DJTool validObj:headImageURL]) {
            [dic setValue:headImageURL.absoluteString forKey:@"user_image"];
        }
    }
    [dic setValue:@"3" forKey:@"user_type"];
    [[NSUserDefaults standardUserDefaults] setValue:dic forKey:@"user_info"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self loginWithGoogleSignIn:userId];
}

- (void)signIn:(GIDSignIn *)signIn didDisconnectWithUser:(GIDGoogleUser *)user withError:(NSError *)error {
    
    NSLog(@"sign didDisconnectWithUser %@-%@",user.userID,error);
    
}

#pragma mark - UITextView delegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction  API_AVAILABLE(ios(10.0)){
    
    if ([[URL scheme] isEqualToString:@"protocol"]) {
        DJWebViewController *webVC = [[DJWebViewController alloc] init];
        webVC.titleString = @"用户协议";
        webVC.urlString = @"https://kaleido.live/agreement.html";
        [self.navigationController pushViewController:webVC animated:YES];
    } else if ([[URL scheme] isEqualToString:@"privacy"]) {
        DJWebViewController *webVC = [[DJWebViewController alloc] init];
        webVC.titleString = @"隐私政策";
        webVC.urlString = @"https://kaleido.live/privacy.html";
        [self.navigationController pushViewController:webVC animated:YES];
    }
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    
    if ([[URL scheme] isEqualToString:@"protocol"]) {
        DJWebViewController *webVC = [[DJWebViewController alloc] init];
        webVC.titleString = @"用户协议";
        webVC.urlString = @"https://kaleido.live/agreement.html";
        [self.navigationController pushViewController:webVC animated:YES];
    } else if ([[URL scheme] isEqualToString:@"privacy"]) {
        DJWebViewController *webVC = [[DJWebViewController alloc] init];
        webVC.titleString = @"隐私政策";
        webVC.urlString = @"https://kaleido.live/privacy.html";
        [self.navigationController pushViewController:webVC animated:YES];
    }
    return NO;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wxLogin" object:self];
}

@end
